package com.qf.service.impl;

/*
 *  @author Administrator
 *  @version V1.0
 *  @Project smartdeviceplatgorm
 *  @Package com.qf.service.impl
 *  @Description
 *  @Date2022/3/17 0017 14:55
 */

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.bean.SysCategory;
import com.qf.bean.SysUserInfo;
import com.qf.cache.CategoryCache;
import com.qf.enums.EmptyType;
import com.qf.event.CategoryCacheChangeEvent;
import com.qf.exception.AddDataException;
import com.qf.exception.DeleteDataException;
import com.qf.exception.UpdateDataException;
import com.qf.mapper.SysCategoryMapper;
import com.qf.service.SysCategoryService;
import com.qf.utils.ResultCode;
import com.qf.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class SysCategoryServiceImpl implements SysCategoryService {

    private ApplicationContext applicationContext;
    private SysCategoryMapper sysCategoryMapper;
    private CategoryCache categoryCache;

    @Autowired
    public void setCategoryCache(CategoryCache categoryCache) {
        this.categoryCache = categoryCache;
    }

    @Autowired
    public void setSysCategoryMapper(SysCategoryMapper sysCategoryMapper) {
        this.sysCategoryMapper = sysCategoryMapper;
    }

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void addSysCategory(SysCategory sysCategory) {
        //检查是不是传数据了
        Assert.isTrue(!sysCategory.isEmpty(EmptyType.ADD), () -> {
            throw new AddDataException("分类数据名称没有传递", ResultCode.DATA_NULL);
        });
        //检查当前是不是登录了用户,如何判断用户登录了, 所以一定有个地方保存了登录的用户(数据到底保存在什么地方是我们决定的),我们登录完成后放到session了
        //那我们只需要从session中获取
        SysUserInfo loginUser = SecurityUtils.getLoginUser();
        Assert.notNull(loginUser, () -> {
            throw new AddDataException("未登录", ResultCode.LOGIN_NOT);
        });
        //补充数据
        sysCategory.setCreateBy(loginUser.getUsername());
        sysCategory.setCreateTime(new Date());
        sysCategoryMapper.addSysCategory(sysCategory);
        //通知缓存更新
        applicationContext.publishEvent(new CategoryCacheChangeEvent());
    }

    @Override
    @Transactional(readOnly = true)
    public SysCategory findById(Integer id) {
        return categoryCache.get(id);
    }

    @Override
    public PageInfo<SysCategory> findByPage(int pageNum, int pageSize, String categoryName) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysCategory> categoryList = categoryCache.getCategoryListCache();
//        ArrayList<Object> arrayList = new ArrayList<>();//保存有符合过滤条件的数据
//        for (SysCategory sysCategory : categoryList) {
//            if (!StringUtils.hasText(categoryName)||sysCategory.getCategoryName().contains(categoryName)) {//包含指定条件的数据保存起来
//                arrayList.add(sysCategory);
//            }
//        }
        List<SysCategory> collect = categoryList.stream().filter(sysCategory -> {
            return StringUtils.hasText(categoryName) ? sysCategory.getCategoryName().contains(categoryName) : true;
        }).collect(Collectors.toList());
        List<SysCategory> collect1 = collect.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        PageInfo<SysCategory> pageInfo = new PageInfo<>(collect1);
        pageInfo.setTotal(collect.size());
        pageInfo.setPageNum(pageNum);
        return pageInfo;
    }

    @Override
    public int updateSysCategory(SysCategory category) {

        Assert.isTrue(!category.isEmpty(EmptyType.UPDATE),()->{
            throw new UpdateDataException("请填写要修改的数据！", ResultCode.DATA_NULL);
        });
        SysUserInfo loginUser = SecurityUtils.getLoginUser();
        Assert.notNull(loginUser, () -> {
            throw new AddDataException("未登录", ResultCode.LOGIN_NOT);
        });
        category.setCreateTime(new Date());
        category.setUpdateBy(loginUser.getUsername());
        category.setUpdateTime(new Date());
        int result = sysCategoryMapper.updateSysCategory(category);
        //发布事件通知缓存更新一下
        applicationContext.publishEvent(new CategoryCacheChangeEvent());
        return result;
    }

    @Override
    public int deleteByIds(List<Integer> ids) {
        Assert.notEmpty(ids,()->{
            throw new DeleteDataException("请选择要删除的数据!", ResultCode.DATA_NULL);
        });
        SysUserInfo loginUser = SecurityUtils.getLoginUser();
        Assert.notNull(loginUser, () -> {
            throw new AddDataException("未登录", ResultCode.LOGIN_NOT);
        });
        int count = sysCategoryMapper.deleteSysCategory(ids);
        applicationContext.publishEvent(new CategoryCacheChangeEvent());//更新缓存
        return count;
    }
}

//}
